package com.wechat.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.xiezc.entity.respMsg.TextMsg;
import org.xiezc.util.MessageFactory;

/**
 * Set string filter UTF-8
 * 
 * @author tom 2015.12.30
 */
public class ExceptionFilter implements Filter {

	private static Logger logger = Logger.getLogger(ExceptionFilter.class);



	@Override
	public void destroy() {
		logger.info("ExceptionFilter already destroy");
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		try {
			chain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			String url = request.getRequestURI();
			if ("/chat".equals(url)) {
				@SuppressWarnings("unchecked")
				Map<String, String> reqMap=	(Map<String, String>) request.getAttribute("reqMap");
				TextMsg textMsg = MessageFactory.createTextMsg("");
			
				textMsg.addLink("服务器出错", "http://xiezc.vip.natapp.cn/rank.html");
				textMsg.setFromUserName(reqMap.get("ToUserName"));
				textMsg.setToUserName(reqMap.get("FromUserName"));
				PrintWriter pw = response.getWriter();
				String respXml = textMsg.toXml();
				pw.print(respXml);
				pw.flush();
				pw.close();
			} else {
				request.getRequestDispatcher("/WEB-INF/404.jsp").forward(request, response);
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		logger.info("ExceptionFilter; initialize");
	}
}
